(function (mui, $) {

// 删除上传图片
$('body').delegate('.image-item .icon-close', 'tap', function () {
	$(this).closest('.image-item').remove();
});
// 选择头像
$('.btn-add-image').on('tap', function () {
	app.wxInit({
    error: function (res) {
      app.log('图片上传失败：', res);
    },
    success: function () {
      app.wxUploadImage(function (res) {
        app.log('上传结果：', res);
        $.ajax({
          'dataType' : 'json',
          'type'     : 'post',
          'url'      : app.uploadUrl('/getWeChatImage'),
          'data'     : { data: { media_id: res.join(',')}}
        })
        .fail(function (res) {
          app.log('图片上传失败：', res);
        })
        .done(function (res) {
          app.log('图片上传成功：', res.data.lists);
          append(res);
        });
      });
    }
  });
});

function getFromCamera () {
	var camera = plus.camera.getCamera();
	camera.captureImage(function(e) {
		upload([{'path':e}]);
	}, function(res) {
		app.log(res);
		app.toast('拍照失败');
	}, {
		filename:'_doc/tx.jpg'
	});
}

function getFromGallery () {
	plus.gallery.pick(function(e) {
		var queue = [];
		for (var i in e.files) {
			queue.push({'path':e.files[i]});
		}
		upload(queue);
	}, function(e) {}, {
		filter: "image", multiple:true
	});
};

function cutter (images) {
	upload(images);
}

function upload (images) {
	app.log('上传数据：', images);
	plus.nativeUI.showWaiting('正在处理...');
	function _cb (result, status) {
		var res = result.responseText;
		plus.nativeUI.closeWaiting();
		
		try { res = JSON.parse(res); } catch (e) { status = 404 }
		
		if (status == 200) {
			//plus.nativeUI.toast('上传文件成功');
			app.log('上传结果：', res);
			
			if (500 == res.code) { app.toast('你还未登录'); return; }
			if (300 == res.code) { app.toast(res.msg); return; }
			if (200 != res.code) { app.toast('请求失败'); return; }
			//if (res.msg) { app.toast(res.msg); }
			append(res);
		} else {
			app.log('上传头像失败：', result.responseText);
			app.toast('上传图片失败');
		}
	}
	var task = plus.uploader.createUpload(app.url('Files/Upload/appUpload'), { method:"POST",blocksize:204800,priority:100 }, _cb);
	for (var i in images) {
		task.addFile(images[i].path, {'name':images[i].name});
	}
	//task.addData('thumb', image);
	task.addData('token', app.store('token'));
	task.addData('action', 'uploadimage');
	
	task.start();
}

function append (images) {
	var tpl = app.tpl('tpl-image', images.data);
	$('.btn-add-image').before(tpl);
}

mui.plusReady(function () {
	report();
})
// 提交秀图内容
$('.btn-submit').on('tap', function () {
	var dom = this, view = plus.webview.currentWebview();
	var data = {
		'activity_id' : view.extras.id,
		'title'       : $('[name=title]').val(),
		'content'     : $('[name=content]').val(),
		'images'      : [],
	};
	$('.image-item').each(function (idx, item) {
		data.images.push($(item).attr('data-path'));
	});
	
	app.log('我要来秀：', {'token':app.store('token'), 'data':data});
	plus.nativeUI.showWaiting();
	$(dom).prop('disabled', true);
	$.ajax({
		'dataType' : 'json',
		'type'     : 'post',
		'url'      : app.url('App/Activity/Show/create'),
		'data'     : {'token':app.store('token'), 'data':data}
	})
	.fail(function (res) {
		plus.nativeUI.closeWaiting();
		app.log('提交失败：', res);
		app.toast('提交失败');
		$(dom).prop('disabled', false);
	})
	.done(function (res) {
		plus.nativeUI.closeWaiting();
		app.log('提交结果：', res);
		$(dom).prop('disabled', false);
		
		if (500 == res.code) { app.toast('你还未登录'); return; }
		if (300 == res.code) { app.toast(res.msg); return; }
		if (200 != res.code) { app.toast('请求失败'); return; }
		if (res.msg) { app.toast(res.msg); }
		
		plus.webview.currentWebview().close();
	})
	;
});

function report () {
	var view = plus.webview.currentWebview();
	
	plus.nativeUI.showWaiting();
	$.ajax({
		'dataType' : 'json',
		'type'     : 'post',
		'url'      : app.url('App/Activity/Show/jion'),
		'data'     : {'token':app.store('token'), 'data':{'activity_id':view.extras.id}}
	})
	.fail(function (res) {
		plus.nativeUI.closeWaiting();
		app.log('加入失败：', res);
		app.toast('加入失败');
	})
	.done(function (res) {
		plus.nativeUI.closeWaiting();
		app.log('加入结果：', res);
		
		if (500 == res.code) { app.toast('你还未登录'); return; }
		if (300 == res.code) { app.toast(res.msg); return; }
		if (200 != res.code) { app.toast('请求失败'); return; }
		//if (res.msg) { app.toast(res.msg); }
	})
	;
}

})(mui, $);
